<!--
 虚拟列表
 @Author: mosowe
 @Date:2023-03-07 09:14:40
-->

<template>
	<view class="mosowe-invented-list">
		<scroll-view class="container" :scroll-top="scrollTop" scroll-y="true" @scroll="handleScroll">
			<div class="mosowe-invented-wrap" :style="{ height:boxHeight+ 'px' }">
				<div class="mosowe-invented-content" :style="{ transform: 'translateY(' + offsetY + 'px)' }">
					<template v-if="showFlag">
						<view class="mosowe-invented-item" :style="{height:itemHeight+'px'}"
							v-for="(item, index) in showList" :key="index">
							<slot :item="item"></slot>
						</view>
					</template>
				</div>
			</div>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		props: {
			list: {
				type: Array,
				default: () => []
			},
			cacheNum: {
				// 前后缓存数目
				type: Number,
				default: 50
			}
		},
		data() {
			return {
				showList: [], // 展示的数据列表
				itemHeight: 50, // 每条数据高度，计算第一条数据的高度，以第一条数据高度为主
				offsetY: 0,
				topLong: 20,
				showFlag: false,
				scrollTop: 0,
				old: {
					scrollTop: 0
				}
			};
		},
		computed: {
			boxHeight() {
				return this.list.length * this.itemHeight
			},
			pageNum() {
				return this.cacheNum;
			},
			proxyList() {
				return this.list
			}
		},
		watch: {
			list: {
				handler() {
					let localPageNum = 50
					this.setShowList(localPageNum);
					this.$nextTick(() => {
						this.scrollTop = 50 * this.itemHeight
					this.showFlag = true
					});
				},
				deep: true
			}
		},
		methods: {
			handleScroll(e) {
				this.old.scrollTop = e.detail.scrollTop
				const scrollTop = Math.floor(e.detail.scrollTop);
				let startIndex = Math.floor(scrollTop / this.itemHeight);
				if ((startIndex - this.topLong) >= 0) {
					this.offsetY = (startIndex - this.topLong) * this.itemHeight
					this.showList = this.list.slice(startIndex - this.topLong, this.pageNum + startIndex);
				} else {
					this.offsetY = 0
					this.showList = this.list.slice(0, this.pageNum + startIndex);
				}
				this.$emit('scroll', scrollTop);
				// console.log(startIndex)
			},
			setShowList(startIndex) {
				this.showList = this.list.slice(startIndex, startIndex + this.pageNum);
			}
		}
	};
</script>

<style lang="scss" scoped>
	.mosowe-invented-list {
		overflow: hidden;
		height: 100%;
		width: 100%;

		.container {
			width: 100%;
			height: 100%;

			.mosowe-invented-wrap {
				box-sizing: border-box;
				.mosowe-invented-content {
					.mosowe-invented-item {
						display: flex;
						align-items: center;
					}
				}
			}
		}
	}
</style>